<?php
	
	define('SPAM_PROTECTION_INTERVAL', 10);

	class Users{
		private $db;
		
		public function __construct(){
			$this->db =& Application::getInstance()->database('default');
		}
		
		/**
		 *
		 * @param int $userId user id
		 * @return bool whether the user exists in the database or not.
		 */
		public function exists($userId){
			$stmt = $this->db->query('SELECT id FROM users WHERE id = ?', array($userId));
			
			if($stmt['rowCount'] > 0){
				return true;
			}
			
			return false;
		}
		
		/**
		 * 
		 * @param type $userId
		 * @return array with "friends" and "profile" (both bool, 
		 * whether they have to get updated or not)
		 */
		public function readUserUpdates($userId){
			$stmt = $this->db->query('SELECT updateFriends, updateProfile FROM users WHERE id = ?', array($userId));
			return array('friends' => (bool)$stmt['result'][0]['updateFriends'], 'profile' => (bool)$stmt['result'][0]['updateProfile']);
		}
		
		/**
		 *
		 * @param array id, firstName, name, email, friendCount, sex, locale,
		 * relationshipStatus, interestedInMale, interestedInFemale, sigOtherId,
		 * hometown, location, isPublic
		 * @return int lastInsertId
		 */
		public function create($profile){
			$stmt = $this->db->query('
				INSERT INTO users(
					id,
					firstName,
					name,
					email,
					friendCount,
					sex,
					locale,
					relationshipStatus,
					interestedInMale,
					interestedInFemale,
					sigOtherId,
					birthday,
					hometown,
					location,
					isPublic,
					createdOn
				) VALUES (
					:id,
					:firstName,
					:name,
					:email,
					:friendCount,
					:sex,
					:locale,
					:relationshipStatus,
					:interestedInMale,
					:interestedInFemale,
					:sigOtherId,
					:birthday,
					:hometown,
					:location,
					:isPublic,
					NOW()
				)
			', $profile);
			
			return $stmt['lastInsertId'];
		}
		
		/**
		 *
		 * @param int $userId
		 */
		public function deleteFriends($userId){
			$this->db->query('DELETE FROM usersFriends WHERE userId = ?', array($userId));
		}
		
		/**
		 *
		 * @param id $userId
		 * @param array $friends
		 */
		public function createFriends($userId, $friends){
			if(is_array($friends) && count($friends) > 0){
				$query = 'INSERT INTO usersFriends(userId, friendUserId, name) VALUES ';
				$parameters = array();

				foreach($friends as &$friend){
					$query .= '(?, ?, ?), ';
					$parameters[] = (string)$userId;
					$parameters[] = (string)$friend['uid'];
					$parameters[] = utf8_decode(strtolower($friend['name']));
				}

				$this->db->query(substr($query, 0, -2), $parameters);
			}
		}
		
		/**
		 *
		 * @param type $userId
		 * @param array $fields array with fields names that you want to update
		 * @param type $parameters array with parameters of the fields you want to update
		 */
		public function update($userId, $fields, $parameters){
			$query = 'UPDATE users SET ';
			
			foreach($fields as &$field){
				$query .= $field . ' = ?, ';
			}
			
			$parameters[] = $userId;
			$this->db->query(substr($query, 0, -2) . ' WHERE id = ?', $parameters);
		}
		
		/**
		 *
		 * @param int $userId
		 */
		public function deleteProfile($userId){
			$this->db->query('DELETE FROM users WHERE id = ?', array($userId));
		}
		
		/**
		 * 
		 * @param int $userId
		 */
		public function deleteFull($userId){
			$this->deleteProfile($userId);
			$this->deleteFriends($userId);
		}
		
		/**
		 *
		 * @param type $userId
		 * @param array $fields names of the fields you want to read
		 * @return array
		 */
		public function read($userId, $fields){
			$query = 'SELECT ';
			
			foreach($fields as &$field){
				$query .= $field . ', ';
			}
			
			$stmt = $this->db->query(substr($query, 0, -2) . ' FROM users WHERE id = ?', array($userId));
			
			if($stmt['rowCount'] > 0){
				return $stmt['result'][0];
			}
			
			return false;
		}
		
		/**
		 * 
		 * @param int $userId
		 * @param string $keyword
		 * @return array friendUserId, name
		 */
		public function searchFriends($userId, $keyword){
			$stmt = $this->db->query('SELECT friendUserId, name FROM usersFriends WHERE userId = ? AND name LIKE ? LIMIT 15', array(
				$userId,
				'%' . $keyword . '%'
			));
			
			if($stmt['rowCount'] > 0){
				return $stmt['result'];
			}
			
			return false;
		}
		
		/**
		 * 
		 * @param type $userId
		 * @param type $keyword
		 * @return array
		 */
		public function searchCache($userId, $keyword){
			$companiesCache = $this->db->query("
				SELECT
					C.id,
					C.name,
					C.city,
					C.branch,
					UC.objectType
				FROM
					companies C
				JOIN 
					usersSearchCache UC
				ON 
					C.id = UC.objectId
				WHERE 
					UC.userId = ? 
				AND 
					C.keywords 
				LIKE
					?
				LIMIT
					15
			", array($userId, '%' . $keyword . '%'));
			
			$citiesCache = $this->db->query("
				SELECT 
					C.id,
					C.country,
					C.name,
					UC.objectType
				FROM
					cities C
				JOIN
					usersSearchCache UC 
				ON 
					C.id = UC.objectId
				WHERE
					UC.userId = ?
				AND 
					C.name 
				LIKE 
					?
				LIMIT
					15
			", array($userId, '%' . $keyword . '%'));
			
			return array_merge($companiesCache['result'], $citiesCache['result']);
		}
		
		/**
		 * Function checks whether the user is allowed to create a new activity
		 * we have to check this because we only want to allow the user to 
		 * post a new activity each 10 seconds, we don't want spam or bullshit.
		 * 
		 * @param int $userId
		 * @return bool
		 */
		public function isAllowedToCreateActivity($userId){
			$stmt = $this->db->query('SELECT id FROM activities WHERE createdOn > (NOW() - INTERVAL ' . SPAM_PROTECTION_INTERVAL . ' SECOND)', array($userId));
			
			if($stmt['rowCount'] > 0){
				return false;
			}
			
			return true;
		}
		
		/**
		 *
		 * @param int $userId
		 * @param int $friendUserId
		 * @return bool
		 */
		public function isFriendWith($userId, $friendUserId){
			$stmt = $this->db->query('SELECT id FROM usersFriends WHERE userId = ? AND friendUserId = ?', array($userId, $friendUserId));
			
			if($stmt['rowCount'] > 0){
				return true;
			}
			
			return false;
		}
		
		/**
		 * 
		 * @param int $userId
		 * @param int $objectId
		 * @param int $objectType
		 */
		public function createSearchCacheObject($userId, $objectId, $objectType){
			$exists = $this->db->query('SELECT id FROM usersSearchCache WHERE userId = ? AND objectId = ? AND objectType = ?', array(
				$userId, $objectId, $objectType
			));
		
			// Create or update, so our cache keeps updated.
			if($exists['rowCount'] === 0){
				$this->db->query('INSERT INTO usersSearchCache(userId, objectId, objectType, createdOn, lastUpdated) VALUES
					(?, ?, ?, NOW(), NOW())
				', array($userId, $objectId, $objectType));
			} else {
				$this->db->query('UPDATE usersSearchCache SET lastUpdated = NOW() WHERE id = ?', array($exists['result'][0]['id']));
			}
		}
		
		/**
		 *
		 * @param int $userId
		 * @return string name of the first found friend
		 */
		public function readFirstfriend($userId){
			$stmt = $this->db->query('SELECT name FROM usersFriends WHERE userId = ? LIMIT 1', array($userId));
			
			if($stmt['rowCount'] > 0){
				return $stmt['result'][0]['name'];
			}
			
			return null;
		}
		
		/**
		 *
		 * @param int $userId
		 * @param int $friendId
		 * @return array id, name
		 */
		public function readUserFriend($userId, $friendId){
			$stmt = $this->db->query('SELECT name FROM usersFriends WHERE userId = ? AND friendUserId = ?', array($userId, $friendId));
			
			if($stmt['rowCount'] > 0){
				return $stmt['result'][0];
			}
			
			return null;
		}
		
		/**
		 *
		 * @param int $userId
		 * @return array A.*, U.name
		 */
		public function readNotifications($userId){
			$stmt = $this->db->query('
				SELECT 
					AL.id as notId, A.*, U.name, U.sex
				FROM
					activitiesUsersLink AL
				JOIN
					activities A
				ON
					A.id = AL.activityId
				JOIN
					users U
				ON
					U.id = A.createdBy
				WHERE
					AL.userId = ?
				AND
					AL.accepted = 0
			', array($userId));
			
			if($stmt['rowCount'] > 0){
				$locations = new Locations();
				
				foreach($stmt['result'] as &$a){
					if($a['destType'] === '1'){
						$a['obj'] = $locations->readCompany($a['destId']);
					} else if($a['destType'] === '2'){
						$a['obj'] = $this->readFriend($a['destId']);
					} else if($a['destType'] === '3'){
						$a['obj'] = $locations->readCity($a['destId']);
					}
				}
				
				return $stmt['result'];
			}
			
			return null;
		}
		
		/**
		 * Hardcore function to get a friend out of the usersFriends table, pretty hacky, might be improved...
		 * @param type $friendUserId
		 * @return array id, name or null
		 */
		public function readFriend($friendUserId){
			$stmt = $this->db->query('SELECT id, name FROM usersFriends WHERE friendUserId = ?', array($friendUserId));
			
			if($stmt['rowCount'] > 0){
				return $stmt['result'][0];
			}
			
			return null;
		}
		
		/**
		 * 
		 * @param int $userId
		 * @param int $notId
		 * @return bool 
		 */
		public function notificationBelongsToUser($userId, $notId){
			$stmt = $this->db->query('SELECT id FROM activitiesUsersLink WHERE id = ? AND userId = ?', array($notId, $userId));
			
			if($stmt['rowCount'] > 0){
				if($stmt['result'][0]['id'] === $notId){
					return true;
				}
			}
			
			return false;
		}
		
		/**
		 *
		 * @param type $id
		 * @param mixed $decision 0 or 1
		 */
		public function updateNotification($id, $decision){
			if($decision === '0'){
				$this->db->query('DELETE FROM activitiesUsersLink WHERE id = ?', array($id));
			} else if($decision === '1'){
				$this->db->query('UPDATE activitiesUsersLink SET accepted = 1', array($id));
			}
		}
		
		/**
		 *
		 * @param int $userId
		 * @param string $keyword
		 */
		public function extendedSearch($userId, $keyword, $country){
			// Search location.
			$companies = $this->db->query('SELECT id, adres, name, country, zipcode, city, branch, createdByUser FROM companies WHERE keywords LIKE ? LIMIT 50', array(
				'%' . $keyword . '%'
			));
			
			// Search users.
			$users = $this->db->query('SELECT id, name, birthday, isPublic, location, relationshipStatus FROM users WHERE name LIKE ? LIMIT 50', array(
				'%' . $keyword . '%'
			));
			
			// Search cities.
			$cities = $this->db->query('SELECT id, name, country FROM cities WHERE name LIKE ? AND country = ? LIMIT 50', array(
				'%' . $keyword . '%',
				$country
			));
			
			return array('companies' => $companies['result'], 'users' => $users['result'], 'cities' => $cities['result']);
		}
		
//		public function readUserStats($userId){
//			$commonStatistics = $this->db->query("
//				SELECT
//					SUM(CASE WHEN A.destType = '2' THEN 1 ELSE 0 END) AS friendActivityCount
//				FROM
//					activitiesUsersLink AL
//				JOIN
//					activities A
//				ON
//					AL.activityId = A.id
//				WHERE
//					AL.userId = ?
//			", array($userId));
			
			
			
//			$stmt = $this->db->query("
//				SELECT 
//					COUNT(*) AS total, 
//					SUM(CASE WHEN `destinationObjectType` = '2' THEN 1 ELSE 0 END) AS friendActivities,
//					SUM(CASE WHEN `destinationObjectType` = '1' THEN 1 ELSE 0 END) AS locationActivities
//				FROM `happenings` WHERE `userId` = ?", array($userId));
//			
//			// Favorite tag.
//			$favTag = $this->db->query('
//				SELECT
//					T.name, T.id
//				FROM
//					happeningsTags T
//				LEFT JOIN
//					happenings
//				ON
//					T.
//				SELECT `happeningsTags`.`name`, `happeningsTags`.`id`
//				FROM `happeningsTags`
//				LEFT JOIN `happenings`
//				ON `happeningsTags`.`id` = `happenings`.`tag`
//				WHERE `happenings`.`userId` = ?
//				GROUP BY `happeningsTags`.`name` ASC
//				LIMIT 1
//			', array($userId));
//			
//			if($favTag['rowCount'] > 0){
//				$stmt['result'][0]['tag'] = $favTag['result'][0];
//			}
//			
//			return $stmt['result'][0];
	}
	
//	define('SPAM_PROTECTION_INTERVAL', 10);
//	define('FLUSH_CACHE_AT', 300);
//
//	class Users{
//		private $db;
//		
//		public function __construct(){
//			$this->db =& Application::getInstance()->database('default');
//		}
//		
//		public function getNameId($userId){
//			$stmt = $this->db->query('SELECT `name`, `id` FROM `users` WHERE `id` = ?', array($userId));
//			
//			if($stmt['rowCount'] > 0){
//				return $stmt['result'][0];
//			}
//			
//			return null;
//		}
//		
//		public function searchCache($userId, $keyword){
//		
//			// This query can be improved!
//			$companiesCache = $this->db->query('
//				SELECT * FROM
//				companies as C
//				JOIN usersSearchCache as UC ON C.id = UC.objectId
//				WHERE UC.userId = ? AND C.keywords LIKE ?
//				LIMIT 15
//			', array($userId, '%' . $keyword . '%'));
//			
//			$citiesCache = $this->db->query('
//				SELECT * FROM
//				cities as C
//				JOIN usersSearchCache as UC ON C.id = UC.objectId
//				WHERE UC.userId = ? AND C.name LIKE ?
//				LIMIT 15
//			', array($userId, '%' . $keyword . '%'));
//			
//			return array_merge($companiesCache['result'], $citiesCache['result']);
//		}
//		
//		public function flushUserCache($userId){
//			$this->db->query('DELETE FROM `usersSearchCache` WHERE `userId` = ?', array($userId));
//		}
//		
//		public function addToSearchCache($userId, $objectId, $objectType){
//		
//			// Do we have to flush cache sometimes?
//			// Do we have to flush cache when it exceeds an count?
//			// First check whether it was already added, than we don't have to add it.
//			$exists = $this->db->query('SELECT `id` FROM `usersSearchCache` WHERE `userId` = ? AND `objectId` = ? AND `objectType` = ?', array(
//				$userId, $objectId, $objectType
//			));
//		
//			if($exists['rowCount'] === 0){
//				$this->db->query('INSERT INTO `usersSearchCache`(`userId`, `objectId`, `objectType`, `createdOn`, `lastUpdated`) VALUES
//					(?, ?, ?, NOW(), NOW())
//				', array($userId, $objectId, $objectType));
//				
//			// We update the createdOn, so we have a nice up-to-date + not fucked up alot cache (just create a cronjob that deletes them < 30 days)
//			} else {
//				$this->db->query('UPDATE `usersSearchCache` SET `lastUpdated` = NOW() WHERE `id` = ?', array($exists['result'][0]['id']));
//			}
//		}
//		
//		public function get($userId){
//			$stmt = $this->db->query('SELECT * FROM `users` WHERE `id` = ?', array($userId));
//			
//			if($stmt['rowCount'] > 0){
//			
//				if($stmt['result'][0]['sigOtherId'] !== ''){
//					if($this->exists($stmt['result'][0]['sigOtherId'])){
//						$stmt['result'][0]['sigOther'] = $this->getNameId($stmt['result'][0]['sigOtherId']);
//					}
//				}
//
//				return $stmt['result'][0];
//			}
//			
//			return null;
//		}
//		
//		public function getStats($userId){
//			// Activitycount stats.
//			$stmt = $this->db->query("
//				SELECT 
//					COUNT(*) AS total, 
//					SUM(CASE WHEN `destinationObjectType` = '2' THEN 1 ELSE 0 END) AS friendActivities,
//					SUM(CASE WHEN `destinationObjectType` = '1' THEN 1 ELSE 0 END) AS locationActivities
//				FROM `happenings` WHERE `userId` = ?", array($userId));
//			
//			// Favorite tag.
//			$favTag = $this->db->query('
//				SELECT `happeningsTags`.`name`, `happeningsTags`.`id`
//				FROM `happeningsTags`
//				LEFT JOIN `happenings`
//				ON `happeningsTags`.`id` = `happenings`.`tag`
//				WHERE `happenings`.`userId` = ?
//				GROUP BY `happeningsTags`.`name` DESC
//				LIMIT 1
//			', array($userId));
//			
//			if($favTag['rowCount'] > 0){
//				$stmt['result'][0]['tag'] = $favTag['result'][0];
//			}
//			
//			return $stmt['result'][0];
//		}
//		
//		public function getName($userId){
//			$stmt = $this->db->query('SELECT `firstName` FROM `users` WHERE `id` = ?', array($userId));
//			return ucwords($stmt['result'][0]['firstName']);
//		}
//		
//		public function exists($userId){
//			$stmt = $this->db->query('SELECT `id` FROM `users` WHERE `id` = ?', array($userId));
//			
//			if($stmt['rowCount'] > 0){
//				return true;
//			}
//			
//			return false;
//		}
//		
//		public function getFirstFriend($userId){
//			$stmt = $this->db->query('SELECT `name` FROM `usersFacebookFriends` WHERE `userId` = ? LIMIT 1', array($userId));
//			
//			if($stmt['rowCount'] > 0){
//				return ucwords($stmt['result'][0]['name']);
//			}
//			
//			return null;
//		}
//		
//		public function setUserIsPublic($userId, $bool){
//			$this->db->query('UPDATE `users` SET `isPublic` = ? WHERE `id` = ?', array((int)$bool, $userId));
//		}
//		
//		public function userCreatedLocationCountTotal($userId){
//			$stmt = $this->db->query('SELECT `id` FROM `companies` WHERE `createdByUser` = ?', array($userId));
//			return (int)$stmt['rowCount'];
//		}
//		
//		public function userCreatedLocationCountToday($userId){
//			$stmt = $this->db->query('SELECT `id` FROM `companies` WHERE `createdByUser` = ? AND UNIX_TIMESTAMP(`createdOn`) BETWEEN UNIX_TIMESTAMP(CURDATE()) AND UNIX_TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL + 24 HOUR))', array($userId));
//			return (int)$stmt['rowCount'];
//		}
//		
//		public function isUserPublic($userId){
//			$stmt = $this->db->query('SELECT `isPublic` FROM `users` WHERE `id` = ?', array($userId));
//			
//			if($stmt['result'][0]['isPublic']){
//				return true;
//			}
//			
//			return false;
//		}
//		
//		// Spam protection with interval for the user so no streams will get spammed!
//		public function allowedToPost($userId){
//			$stmt = $this->db->query('SELECT `id` FROM `happenings` WHERE `createdOn` > (NOW() - INTERVAL ' . SPAM_PROTECTION_INTERVAL . ' SECOND)', array($userId));
//			
//			if($stmt['rowCount'] > 0){
//				return false;
//			}
//			
//			return true;
//		}
//		
//		public function getActivities($userId, $filter, $limit, $objType = null, $objId = null, $date = null, $extraFilters = null){
//		
//	/*
//		// The field selection is always the same, except for the statistics query.
//			$queryFieldSelection = '
//				SELECT 
//					H.id, H.userId, H.date, H.time, H.endDate, H.endTime, H.destinationObjectId, H.destinationObjectType, H.tag,
//					U.id as userId, U.firstName, U.name as userName,
//					T.id as tagId, T.name as tagName
//			';
//			
//			// The field selection for the stats query is alwyas the same.
//			$statsQueryFieldSelection = "
//				SELECT
//					(SUM(CASE WHEN U.sex ='male' THEN 1 ELSE 0 END)) as males,
//					(SUM(CASE WHEN U.sex ='female' THEN 1 ELSE 0 END)) as females,
//					(SUM(CASE WHEN U.relationShipStatus ='single' THEN 1 ELSE 0 END)) as singles,
//					COUNT(*) as count
//			";
//			
//			// Limit part of the query.
//			$queryLimit = '
//				LIMIT :limit
//			';
//			
//			$queryFilter = '';
//			
//			// Lets attach the date filter.
//			switch($filter){
//				case 'mostRecent':
//					break;
//				case 'today':
//					$queryFilter = ' AND DATE(H.date) = DATE(CURDATE())';
//					break;
//				case 'tomorrow':
//					$queryFilter = ' AND DATE(H.date) = (CURDATE() + INTERVAL 1 DAY)';
//					break;
//				case 'yesterday':
//					$queryFilter = ' AND DATE(H.date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)';
//					break;
//				case 'nextWeekend':
//					$queryFilter = " AND UNIX_TIMESTAMP(H.DATE) BETWEEN '" . strtotime('next saturday') . "' AND '" . (strtotime('next monday') - 1) . "'";
//					break;
//				case 'prevWeekend':
//					$queryFilter = " AND UNIX_TIMESTAMP(H.DATE) BETWEEN '" . strtotime('previous saturday') . "' AND '" . (strtotime('previous monday') - 1) . "'";
//					break;
//				case 'date':
//					$queryFilter = ' AND DATE(H.date) = DATE(:date)';
//					break;
//					
//				// If the filter was unknown, just return null.
//				default:
//					return null;
//			}
//			
//			$extraFilter = '';
//			
//			// Lets not display anything at all.
//			if($extraFilters['displayMales'] === 'false' && $extraFilters['displayFemales'] === 'false'){
//				return null;
//			}
//			
//			// Only show males...
//			if($extraFilters['displayMales'] === 'true' && $extraFilters['displayFemales'] === 'false'){
//				$extraFilter = " AND U.sex = 'male'";
//			// Display all.
//			} else 
//			if($extraFilters['displayMales'] === 'true' && $extraFilters['displayFemales'] === 'true'){
//				// Do nothing (default is show all sex)
//			// Display only females.
//			} else
//			if($extraFilters['displayMales'] === 'false' && $extraFilters['displayFemales'] === 'true'){
//				$extraFilter = " AND U.sex = 'female'";
//			}
//			
//			// Display singles only: NOT FORGET .= because we can COMBINE all those filters.
//			if($extraFilters['displaySinglesOnly'] === 'true'){
//				$extraFilter .= " AND U.relationshipStatus = 'single'";
//			}
//			
//			$query = '';
//			$statsQuery = '';
//			$parameterId = '';
//			$order = 'ORDER BY H.createdOn DESC';
//			
//			// If we are getting the stream of an object (user, city or company) ...
//			if($objType !== null){
//			
//				// If we are getting the stream of an CITY or COMPANY
//				if($objType === 1 || $objType === 3){
//				
//					// Display everyone.
//					if($extraFilters['displayFriendsOnly'] === 'false'){
//						$query = $queryFieldSelection . '
//							FROM 
//								happenings H
//							JOIN
//								users U
//							ON
//								U.id = H.userId
//							LEFT JOIN
//								happeningsTags T
//							ON
//								H.tag = T.id
//							WHERE
//								H.destinationObjectId = :id
//						' . $queryFilter . $extraFilter . $order . $queryLimit;
//						
//						$statsQuery = $statsQueryFieldSelection . '
//							FROM
//								happenings H
//							JOIN
//								users U
//							ON
//								U.id = H.userId
//							WHERE 
//								H.destinationObjectId = :id
//						' . $queryFilter . $extraFilter;
//					
//					// Display friends only.
//					} else{
//						$query = $queryFieldSelection . '
//							FROM 
//								usersFacebookFriends UF
//							JOIN
//								happenings H
//							ON
//								H.userId = UF.friendUserId
//							JOIN 
//								users U
//							ON
//								U.id = H.userId
//							LEFT JOIN
//								happeningsTags T
//							ON
//								H.tag = T.id
//							WHERE
//								UF.userId = :userId
//							AND
//								H.destinationObjectId = :id
//						' . $queryFilter . $extraFilter . $order . $queryLimit;
//						
//						$statsQuery = $statsQueryFieldSelection . '
//							FROM 
//								usersFacebookFriends UF
//							JOIN
//								happenings H
//							ON
//								H.userId = UF.friendUserId
//							JOIN 
//								users U
//							ON
//								U.id = H.userId
//							WHERE
//								UF.userId = :userId
//							AND
//								H.destinationObjectId = :id
//						' . $queryFilter . $extraFilter;
//					}
//					
//				// If we are getting the stream of a USER
//				} else {
//					$query = $queryFieldSelection . '
//						FROM 
//							happenings H
//						JOIN 
//							users U
//						ON
//							U.id = H.userId
//						LEFT JOIN
//							happeningsTags T
//						ON
//							H.tag = T.id
//						WHERE
//							H.userId = :id
//					' . $queryFilter . $order . $queryLimit;
//
//					$statsQuery = $statsQueryFieldSelection . '
//						FROM
//							happenings H
//						JOIN
//							users U
//						ON
//							U.id = H.userId
//						WHERE 
//							H.userId = :id
//					' . $queryFilter;
//				}
//				
//				$parameterId = $objId;
//				
//			// We are getting the stream of the homepage.
//			} else {
//				$query = $queryFieldSelection . '
//					FROM 
//						usersFacebookFriends UF
//					JOIN
//						happenings H
//					ON
//						H.userId = UF.friendUserId
//					JOIN 
//						users U
//					ON
//						U.id = H.userId
//					LEFT JOIN
//						happeningsTags T
//					ON
//						H.tag = T.id
//					WHERE
//						UF.userId = :id
//				' . $queryFilter . $order . $queryLimit;
//				
//				$statsQuery = $statsQueryFieldSelection . '
//					FROM
//						usersFacebookFriends UF
//					JOIN
//						happenings H
//					ON
//						H.userId = UF.friendUserId
//					JOIN
//						users U
//					ON
//						U.id = H.userId
//					WHERE
//						UF.userId = :id
//				' . $queryFilter;
//				
//				$parameterId = $userId;
//			}
//
//			// Here we are not using the query method in our Mysql_Database class since the limit must be 
//			// casted to int with PDO::PARAM_INT else it will still be casted to a string an enquoted, which will return a query error
//			// LIMIT '100' is not correct.
//			$stmt = $this->db->prepare($query);
//			$stmt->setFetchMode(PDO::FETCH_ASSOC);
//			$stmt->bindValue('limit', (int)$limit, PDO::PARAM_INT);
//			$stmt->bindValue('id', $parameterId);
//			
//			// Lets not forget to add another parameter if we are showing friends only.
//			if($extraFilters['displayFriendsOnly'] === 'true'){
//				$stmt->bindValue('userId', $userId);
//			}
//			
//			if($filter === 'date'){
//				$stmt->bindValue('date', $date);
//			}
//				
//			$stmt->execute();
//			$activities = $stmt->fetchAll();
//			
//			// Now get the statistics of the stream that the user is getting.
//			$stmt = $this->db->prepare($statsQuery);
//			$stmt->setFetchMode(PDO::FETCH_ASSOC);
//			$stmt->bindValue('id', $parameterId);
//			
//			// Lets not forget to add another parameter if we are showing friends only.
//			if($extraFilters['displayFriendsOnly'] === 'true'){
//				$stmt->bindValue('userId', $userId);
//			}
//			
//			if($filter === 'date'){
//				$stmt->bindValue('date', $date);
//			}
//			
//			$stmt->execute();
//			$stats = $stmt->fetchAll();
//			
//			// 
//			if($activities){
//				foreach($activities as &$a){
//					$withWhoStmt = $this->db->query('
//						SELECT 
//							`id`, `name`
//						FROM
//							`happeningsWithWho`
//						WHERE
//							`happeningId` = ?
//					', array($a['id']));
//	
//					
//					if($withWhoStmt['rowCount'] > 0){
//						$a['withWho'] = $withWhoStmt['result'];
//					}
//				}
//				
//				return array('activities' => $activities, 'stats' => $stats[0]);
//			}
//			
//			return false;
//*/
//		}
//		
//		public function searchUserFriends($userId, $keyword){
//			$stmt = $this->db->query('SELECT `friendUserId`, `name` FROM `usersFacebookFriends` WHERE `userId` = ? AND `name` LIKE ? LIMIT 15', array($userId, '%' . $keyword . '%'));
//			
//			if($stmt['rowCount'] > 0){
//				foreach($stmt['result'] as &$friend){
//					$friend['onHikle'] = $this->exists($friend['friendUserId']);
//				}
//			
//				return $stmt['result'];
//			}
//			
//			return false;
//		}
//		
//		public function getUserFriend($userId, $friendId){
//			$stmt = $this->db->query('SELECT * FROM `usersFacebookFriends` WHERE `userId` = ? AND `friendUserId` = ?', array($userId, $friendId));
//			
//			if($stmt['rowCount'] > 0){
//				return $stmt['result'];
//			}
//			
//			return null;
//		}
//		
//		public function getUserFriends($userId){
//			$stmt = $this->db->query('SELECT `friendUserId` FROM `usersFacebookFriends` WHERE `userId` = ?', array($userId));
//			
//			if($stmt['rowCount'] > 0){
//				return $stmt['result'];
//			}
//			
//			return false;
//		}
//		
//		public function getUserUpdates($userId){
//			$stmt = $this->db->query('SELECT `updateFriends`, `updateProfile` FROM `users` WHERE `id` = ?', array($userId));
//			return $stmt['result'][0];
//		}
//		
//		public function insertFriends($userId, $friends){
//		
//			// Lets delete all the friends of the users first!
//			$this->db->query('DELETE FROM `usersFacebookFriends` WHERE `userId` = ?', array($userId));
//			
//            $query = 'INSERT INTO `usersFacebookFriends`(`userId`, `friendUserId`, `name`) VALUES ';
//            $parameters = array();
//            
//            foreach($friends as &$friend){
//            	$query .= '(?, ?, ?), ';
//            	$parameters[] = (string)$userId;
//            	$parameters[] = (string)$friend['uid'];
//            	$parameters[] = utf8_decode(strtolower($friend['name']));
//            }
//            
//            $stmt = $this->db->query(substr($query, 0, -2), $parameters);
//            
//            // Lets not forget to update the updateProfile to 0.
//       		$this->db->query('UPDATE `users` SET `updateFriends` = 0 WHERE `id` = ?', array($userId));
//		}
//		
//		public function insert($profile){
//		
//			$public = 0;
//		
//			if($this->exists($profile['id'])){
//			
//				// Delete (since this is also the update function)
//				$this->db->query('DELETE FROM `users` WHERE `id` = ?', array($profile['id']));
//				
//				if($this->isUserPublic($profile['id'])){
//					$public = 1;
//				}
//			}
//			
//			$this->db->query('INSERT INTO `users`(
//			`id`, `firstName`, `name`, `email`, `friendCount`, `sex`, 
//			`locale`, `relationshipStatus`, `interestedInMale`, `interestedInFemale`, `sigOtherId`,
//			`birthday`, `hometown`, `location`, `isPublic`, 
//			`updateFriends`, `updateProfile`, `createdOn`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, NOW())', array(
//				$profile['id'],
//				$profile['firstName'],
//				$profile['name'],
//				$profile['email'],
//				$profile['friendCount'],
//				$profile['sex'],
//				$profile['locale'],
//				$profile['relationshipStatus'],
//				$profile['interestedInMale'],
//				$profile['interestedInFemale'],
//				$profile['sigOtherId'],
//				$profile['birthday'],
//				$profile['hometown'],
//				$profile['location'],
//				$public
//			));
//		}
//	}

// File end.